package com.kinoshita.manager.config;

import com.kinoshita.common.jwt.JwtTokenUtil;
import com.kinoshita.manager.api.domain.UserLoginSuccessDO;
import com.kinoshita.manager.service.impl.AdminUserDetailsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenAuthenticationFilter extends OncePerRequestFilter {

  @Autowired
  private JwtTokenUtil jwtTokenUtil;

  @Autowired
  private AdminUserDetailsService adminUserDetailsService;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    String tokenStr = request.getHeader("token");
    if (StringUtils.isNotEmpty(tokenStr)) {
      String username = jwtTokenUtil.getUsername(tokenStr);
      UserLoginSuccessDO userLoginSuccessDO = (UserLoginSuccessDO) adminUserDetailsService.loadUserByUsername(username);
      //获取鉴权信息
      UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
              userLoginSuccessDO, null, userLoginSuccessDO.getAuthorities());
      authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
      logger.info(
          String.format("Authenticated user %s, setting security context", userLoginSuccessDO.getUsername()));
      SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    filterChain.doFilter(request, response);
  }
}